package com.wecom;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class WeComService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private WeComProperties weComProperties;

    @Autowired
    private RestTemplate restTemplate;

    private static final String ACCESS_TOKEN_CRM_KEY = "WE_COM_ACCESS_TOKEN_CRM";

    /**
     * CRMtoken
     *
     * @return
     */
    public synchronized String getCrmAccessToken() {
        String accessToken = stringRedisTemplate.opsForValue().get(ACCESS_TOKEN_CRM_KEY);
        if (StrUtil.isNotBlank(accessToken)) {
            return accessToken;
        } else {
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(WeComUrl.GET_TOKEN_URL, String.class,
                    new HashMap<String, String>() {{
                        put("corpid", weComProperties.getCorpid());
                        put("secret", weComProperties.getCrmSecret());
                    }});
            log.info("企业微信请求结果: {}", responseEntity.getBody());
            if (ObjectUtil.equals(responseEntity.getStatusCode(), HttpStatus.OK)) {
                JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
                Integer errcode = jsonObject.getInt("errcode");
                if (ObjectUtil.equals(errcode, 0)) {
                    accessToken = jsonObject.getStr("access_token");
                    Integer expiresIn = jsonObject.getInt("expires_in");
                    stringRedisTemplate.opsForValue().set(ACCESS_TOKEN_CRM_KEY, accessToken, expiresIn - 100, TimeUnit.SECONDS);
                    return accessToken;
                } else {
                    String errmsg = jsonObject.getStr("errmsg");
                    throw new RuntimeException("接口调用失败:" + errmsg);
                }
            } else {
                throw new RuntimeException("网络异常");
            }
        }
    }

    /**
     * 获取部门id列表
     *
     * @return
     */
    public List<JSONObject> weComDeptList() {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(WeComUrl.DEPARTMENT_LIST_URL, String.class,
                new HashMap<String, String>() {{
                    put("accessToken", getCrmAccessToken());
                }});
        log.info("企业微信请求结果: {}", responseEntity.getBody());
        if (ObjectUtil.equals(responseEntity.getStatusCode(), HttpStatus.OK)) {
            JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
            Integer errcode = jsonObject.getInt("errcode");
            if (ObjectUtil.equals(errcode, 0)) {
                JSONArray jsonArray = jsonObject.getJSONArray("department");
                return jsonArray.toList(JSONObject.class);
            } else {
                String errmsg = jsonObject.getStr("errmsg");
                throw new RuntimeException("接口调用失败:" + errmsg);
            }
        } else {
            throw new RuntimeException("网络异常");
        }
    }
}
